<template>
  <div class="main_box">
    <el-row>
      <el-col :span="5" :xs="24">
        <HospitalTree @hospitalId="getHospitalId"></HospitalTree>
      </el-col>
      <el-col :span="19">
        <div class="search_wrap">
          <el-form
            :inline="true"
            :model="filters"
            class="demo-form-inline"
            ref="searchForm"
          >
            <el-form-item prop="itemName">
              <el-input
                v-model="filters.itemName"
                clearable
                placeholder="项目组名称"
              ></el-input>
            </el-form-item>
            <el-form-item prop="itemCode">
              <el-input
                v-model="filters.itemCode"
                clearable
                placeholder="项目组编号"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                id="searchButton"
                @click="onSearch"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-left" @click="resetForm"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button
              circle
              icon="el-icon-refresh-right"
              @click="reload"
              size="mini"
            ></el-button>
          </el-tooltip>
          <div>
            <el-button
              type="info"
              plain
              size="mini"
              icon="el-icon-s-order"
              @click="handleClickSubItem()"
              >子项目列表</el-button
            >
            <el-button
              type="primary"
              plain
              icon="fa fa-plus"
              v-has="permissionAdd"
              @click="handleClickAdd(3)"
              size="mini"
            >
              新增</el-button
            >
            <el-button
              type="success"
              plain
              size="mini"
              icon="fa fa-plus"
              v-has="permissionImport"
              @click="handleClickImport()"
            >
              导入</el-button
            >
             <el-button
              size="mini"
              plain
              type="info"
              icon="el-icon-folder"
              v-has="permissionExport"
              @click="handleClickExport()"
            >
            
              导出</el-button
            >
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <!-- 列表 -->
        <tree-table
          :tableHeight="'750px'"
          id="scrollDiv"
          ref="tableRow"
          :showCopy="true"
          :key="tableKey"
          :columns="columns"
          :data="treeTableList"
          :eval-func="func"
          :loading="loadingIns"
          :expand-all="expandAll"
          border
        >
          <el-table-column
            label="项目组编号"
            prop="itemCode"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="康来项目组名称"
            prop="reportItemName"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="康来项目组编号"
            prop="reportItemCode"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="原价格"
            prop="itemPrice"
            :formatter="formatPrice"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="合作价格"
            prop="itemSalePrice"
            :formatter="formatPrice"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template slot-scope="scope">
            <span>
              <el-tag :type="formatStates(scope.row.state)" size="mini" effect="dark">
                {{formatState(scope.row.state)}}
              </el-tag>
            </span>
          </template>

        </el-table-column>
          <el-table-column label="创建时间" prop="createDate">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-has="permissionCheck"
                @click="handleClickDetail(scope.row)"
                size="mini"
                >查 看</el-button
              >

              <el-dropdown
                trigger="click"
                size="small"
                v-if="scope.row._level == 1"
              >
                <el-button type="primary">
                  <i class="fa fa-list-ul"></i>更多
                </el-button>
                
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-has="permissionEdit"
                    @click.native="handleClickEdit(scope.row)"
                    >编 辑</el-dropdown-item
                  >
                  <el-dropdown-item
                  v-if="scope.row.state == 0"
                  v-has="permissionState"
                  @click.native="handleClickSuccess(scope.row, 1)"
                  >启 用</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="scope.row.state == 1"
                  v-has="permissionState"
                  @click.native="handleClickDisable(scope.row, 0)"
                  >禁 用</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionUpStatus"
                  v-if="scope.row.state == 0"
                  @click.native="handleClickDelete(scope.row, -1)"
                  >删 除</el-dropdown-item
                >
                  <!-- <el-dropdown-item
                    disabled
                    v-has="permissionUpStatus"
                    @click.native="handleClickDelete(scope.row)"
                    >删 除</el-dropdown-item
                  > -->
                  
                </el-dropdown-menu>
              </el-dropdown>
              <!-- <el-button
                type="success" size="mini" plain
                @click="handleClickAdd(scope.row,1)">关联下级</el-button>
                <el-button
                type="success" size="mini" plain
                @click="handleClickAdd(scope.row,2)">快速增加下级</el-button>
                <el-button
                type="warning" size="mini" plain
                @click="handleClickRemove(scope.row)">解除关联</el-button> -->
            </template>
          </el-table-column>
        </tree-table>
      </el-col>
    </el-row>
    <uploadFile
      ref="uploadFile"
      @uploadFileList="getUploadFileList"
      :accept="uploadAccept"
      folder="hospital"
      :importTemplateUrl="importTemplateUrl"
    >
    </uploadFile>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import treeToArray from "@/utils/customEval";
import treeTable from "@/components/TreeTable";
import HospitalTree from "@/components/HospitalTree";
import HospitalApi from "@/api/institution/hospitalItem";
import uploadFile from "@/components/UploadFile";
import fileDownload from "js-file-download";
import UploadRecordApi from "@/api/system/uploadRecord.js";
import {HOSPITAL_ITEM_IMPORT_TEMPLATE} from "@/constants/constants.js"
export default {
  name: "HospitalItemManagement",
  inject: ["reload"], //注入局部刷新
  data() {
    return {
      importTemplateUrl:"", //导入模板的地址
      // 分批加载数据
      // 开始切割的位置
      startSize:0,
      // 结束位置
      endSize:20,
      totalSize:[],
      hospitalId: "",
      hospitalFindId: "",
      loadingIns: false,
      tableKey: 0,
      pickHospitalList: [],
      filters: {
        itemName: "",
        itemCode: "",
        hospitalId: ""
      },
       uploadAccept: "all", // 上传的文件类型 0.all 1.pdf 2.img 3.video 4.excel
       uploadData: {
        // uploadType: 5, // 医检
        fileDesc: "",
        uploadFile: ""
      },
      columns: [
        {
          text: "项目组名称",
          value: "itemName",
          width: 300,
          align: "center"
        }
      ],
      treeTableList: [],
      func: treeToArray, // 从树形结构转为数组
      expandAll: false, // 全部折叠
      listLoading: true,
      permissionAdd: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_ADD",
      permissionImport: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_IMPORT",
      permissionExport: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_EXPORT",
      permissionCheck: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_SEE",
      permissionEdit: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_EDIT",
      permissionState:"SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_STATE",
      permissionUpStatus: "SYSTEM_MANAGER_ITEM_HOSPITAL_LIST_DELETE"
    };
  },
  components: {
    treeTable,
    HospitalTree,
    uploadFile
  },
  watch: {
    hospitalFindId(val) {
      document.querySelector("#scrollDiv").scrollTop = "0"
      this.listData();
    },
    //to去哪，from从哪来
    $route(to, from) {
      if (
        from.path == "/item/hospitalItemAdd" ||
        from.path == "/items/hospitalItemManagement"
      ) {
        this.listData();
      }
    }
  },
  mounted() {
    this.init();
    this.triggerScroll();
  },
  created() {
    document.onkeydown = function(e) {
      let key = window.event.keyCode;
      if (key == 13) {
        document.getElementById("searchButton").click();
      }
    };
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listData();
    }
  },
  methods: {
      //懒加载1-节流函数
    throttle(fn, delay) {
      let valid = true;
      return function() {
        if (!valid) {
          //休息时间 暂不执行
          return false;
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
          fn();
          valid = true;
        }, delay);
      };
    },
    //懒加载2-触发方法
    triggerScroll() {
      document
        .querySelector("#scrollDiv .el-table__body-wrapper")
        .addEventListener("scroll", this.throttle(this.handleScroll, 1000));
    },
    //懒加载3-主体方法
    handleScroll() {
      let scrollTop = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollTop;
      let scrollHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollHeight;
      let clientHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").clientHeight;
      if (this.totalSize.length == this.treeTableList.length) {
        //表示已到底部
        return;
      }
      if (scrollHeight - clientHeight- scrollTop < 30) {
        // console.log(this.treeTableList.length,380)
        //监听滚动条到底部
        this.starSize = this.starSize + 20;
        this.endSize = this.endSize + 20;
        let arrOne = this.treeTableList;
        let arrTwo = this.totalSize.slice(this.starSize, this.endSize);
        this.treeTableList = arrOne.concat(arrTwo);
        // console.log("总数", this.treeTableList.length);
      }
    },
 


    init() {
      let _this = this;
      _this.importTemplateUrl = HOSPITAL_ITEM_IMPORT_TEMPLATE //获取导入模板的地址
      _this.treeTableList = [];
      if (this.$route.query.id) {
        this.hospitalFindId = this.$route.query.id;
        _this.listData();
      }
      var hospitalIds = localStorage.getItem("hospitalIds");
      if (hospitalIds) {
        this.getHospitalId(hospitalIds);
        // this.$refs.hospitalTree.chooseValue(hospitalIds);
      }
    },
    listData() {
      this.starSize = 0
      this.endSize = 20
      // 获取数据
      let _this = this;
       _this.treeToArray = [];
      _this.totalSize = [];
      let cond = {
        hospitalId: _this.hospitalFindId,
        itemName: _this.filters.itemName,
        itemCode: _this.filters.itemCode
      };
      _this.loadingIns = true;
      HospitalApi.listHospitalItems(cond).then(res => {
        _this.totalSize = res.data;
        if(_this.totalSize.length >= 20){
          _this.treeTableList = _this.totalSize.slice(
            _this.starSize,
            _this.endSize
          );
        }else{
          _this.treeTableList = _this.totalSize;
        }
        // _this.loadingIns = false;
        
      });
    },
    formatState(cellValue) {
      if (cellValue == -1){
        return "删除"
      }else if (cellValue == 0){
        return "禁用"
      }else if (cellValue == 1){
        return "启用"
      }else if (cellValue == 2){
        return "待审核"
      }
    },
    formatStates(cellValue) {
      if (cellValue == -1){
        return "danger"
      }else if (cellValue == 0){
        return "info"
      }else if (cellValue == 1){
        return "success"
      }else if (cellValue == 2){
        return ""
      }
    },
    onSearch() {
      if(!this.hospitalFindId){
        this.$Utils.messageError("请先选择左侧医院单位");
        return false
      }
      this.listData();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.listData();
    },
    formatPrice(row, column, cellValue) {
      // 价格过滤器
      if (!cellValue) {
        return "未知";
      } else {
        return cellValue + " 元/次";
      }
    },
    getHospitalId(val) {
      // 将组件中的id 附给搜索的按钮
      this.hospitalFindId = val;
      localStorage.setItem("hospitalIds", val);
    },
    handleClickSubItem() {
      // 子项目列表
      if(!this.hospitalFindId){
        this.$Utils.messageError("请先选择左侧医院单位");
        return false
      }
      this.$router.push({
        path: "/item/hospitalSubItemManagement"
      });
    },
    handleClickDetail(row) {
      // 查看详情
      if (row._level == 1) {
        this.$router.push({
          path: "/item/hospitalItemDetail",
          query: { id: row.itemId }
        });
      } else if (row._level == 2) {
        this.$router.push({
          path: "/item/hospitalSubItemDetail",
          query: { id: row.itemId }
        });
      }
    },
     handleClickSuccess (row,state) {
        // 启用
      let _this = this
      let cond ={
        id: row.itemId,
        state: state
      };
      this.$confirm("是否启用该项目", message.TITLE_PROMPT).then(() => {
        HospitalApi.deleteHospitalItem(cond).then(res => {
          _this.$message({
            type: "success",
            message: "操作成功"
          });
          _this.listData();
        });
      });
    },
    handleClickDisable(row, state) {
      // 禁用
      let _this = this;
      let cond = {
        id: row.itemId,
        state: state
      };
      this.$confirm("是否禁用该项目", message.TITLE_PROMPT).then(() => {
        HospitalApi.deleteHospitalItem(cond).then(res => {
          _this.$message({
            type: "success",
            message: "操作成功"
          });
          _this.listData();
        });
      });
    },
    handleClickDelete(row, state) {
      // 删除
      let _this = this;
      let cond = {
        id: row.itemId,
        state: state
      };
      this.$confirm("是否删除该项目", message.TITLE_PROMPT).then(() => {
        HospitalApi.deleteHospitalItem(cond).then(res => {
          _this.$message({
            type: "success",
            message: "操作成功"
          });
          _this.listData();
        });
      });
    },
    // handleClickDelete(row) {
    //   // 删除
    //   let _this = this;
    //   _this.$confirm("确认删除该项目组", message.TITLE_PROMPT).then(() => {
    //     HospitalApi.deleteHospitalItem({ id: row.itemId }).then(res => {
    //       _this.$message({
    //         type: "success",
    //         message: "操作成功"
    //       });
    //       _this.listData();
    //     });
    //   });
    // },
    handleClickAdd(value) {
      if(!this.hospitalFindId){
        this.$Utils.messageError("请先选择左侧医院单位");
        return false
      }
      let _this = this;
      // 新增
      if (value == 3) {
        _this.$router.push({
          path: "/item/hospitalItemAdd",
          query:{
            hospitalFindId:this.hospitalFindId
          }
        });
      } else if (value == 1) {
        // 关联下级
      } else if (value == 2) {
        // 快速增加下级 以弹出框形式
      }
    },
    handleClickEdit(row) {
      // 编辑
      let _this = this;
      _this.$router.push({
        path: "/item/hospitalItemAdd",
        query: { id: row.itemId }
      });
    },
    handleClickRemove(row) {
      // 解除关联
      // 判断分类级别只显示在子类列表中
    },
    // 导入
    handleClickImport() {
      let _this = this;
      _this.uploadAccept = "excel";
      _this.$refs.uploadFile.handleCreate();
    },
    // excel导入
    getUploadFileList(val) {
      let _this = this;
      if (!val) {
        _this.$Utils.messageError("请选择文件上传");
        return;
      }
      _this.uploadData.uploadFile = val[0];
      _this.uploadData.fileDesc = "EXCEL导入医院项目组信息";
      UploadRecordApi.addUploadRecord(_this.uploadData)
        .then(res => {
          if (res.status == 0) {
            let params = {
              uploadId: res.data
            };
            HospitalApi.importItemExcel(params)
              .then(res => {
                _this.$Utils.notifySuccess();
                _this.listData()
              })
              .catch(err => {
                console.log(err, " HospitalApi.importItemExcel");
              });
          } else {
            _this.$Utils.notifyError();
          }
        })
        .catch(error => {
          console.log(error, "UploadRecordApi.addUploadRecord");
        });
    },

    // 导出
    handleClickExport() {
      let _this = this;
      _this
        .$confirm("此操作将导出excel文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          HospitalApi.exportItemExcel({hospitalId:this.hospitalFindId}).then(res => {
            let date = new Date()
            fileDownload(res, `医院组合项目表${date.getFullYear()+String(date.getMonth()+1)+date.getDate()}.xlsx`);
          });
        });
    },
  }
};
</script>

<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
